package com.shangcg.util.aviator;

import java.util.HashMap;
import java.util.Map;
import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.function.FunctionUtils;
import com.googlecode.aviator.runtime.type.AviatorBigInt;
import com.googlecode.aviator.runtime.type.AviatorObject;


public class App {

    static{
        //注册函数
        AviatorEvaluator.addFunction(new MinFunction());
    }

    public static void main( String[] args )
    {
        Map<String, Object> sourceMapItem = new HashMap<String, Object>();
        sourceMapItem.put("pt", "mi");
        sourceMapItem.put("ab", "abc");
        sourceMapItem.put("xy", "xyz");
        sourceMapItem.put("int1", 135);
        sourceMapItem.put("int2", 68);
        sourceMapItem.put("decimal2", 19.83);
        sourceMapItem.put("mydate", "2020-10-10 28:35:00");
        sourceMapItem.put("value", 999);
        String expStr = "pt == 'mi'";
        Object result;
        result =  AviatorEvaluator.execute(expStr, sourceMapItem);
        System.out.println(expStr+" ---  "+result);
        //逻辑与 + 简单表达式
        expStr = "pt == 'mi' && ab == 'abc' && int1 > 100 && decimal2 < 20.50";
        result =  AviatorEvaluator.execute(expStr, sourceMapItem);
        System.out.println(expStr+" ---  "+result);
        //逻辑与或组合
        expStr = "pt == 'mi1' || (decimal2 < 20.50 && xy+'X' == 'xyzX')";
        result =  AviatorEvaluator.execute(expStr, sourceMapItem);
        System.out.println(expStr+" ---  "+result);
        //三目运算
        expStr = "pt == 'mi1' ? ab == 'ab' : ab == 'abc'";
        result =  AviatorEvaluator.execute(expStr, sourceMapItem);
        System.out.println(expStr+" ---  "+result);
        //函数
        expStr = "pt != 'mi1' && string.length(xy) >= 5 ";
        result =  AviatorEvaluator.execute(expStr, sourceMapItem);
        System.out.println(expStr+" ---  "+result);
        //自定义函数
        expStr = "pt == 'mi1' || myMin(int2 , int1) > 10 ";
        result =  AviatorEvaluator.execute(expStr, sourceMapItem);
        System.out.println(expStr+" ---  "+result);


    }

    static class MinFunction extends AbstractFunction {
        @Override
        public AviatorObject call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2) {
            Number left = FunctionUtils.getNumberValue(arg1, env);
            Number right = FunctionUtils.getNumberValue(arg2, env);
            return new AviatorBigInt(Math.min(left.doubleValue(), right.doubleValue()));
        }

        public String getName() {
            return "myMin";
        }
    }


}
